package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.youdianda.common.CustomException;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.entity.YddUser;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/home")
@Slf4j
public class HomeController {

    @Autowired
    private YddUserService yddUserService;

    @PostMapping("/index/login")
    public R<Map<String,String>> login(@RequestBody YddUser yddUser, HttpServletRequest request){

        String mobile = yddUser.getMobile();
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile,mobile);
        YddUser one = yddUserService.getOne(wrapper);
        if (one==null){
            throw new CustomException("当前账号不存在");
        }
        String password = yddUser.getPassword();
        // 将客户端传来的密码进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(one.getPassword())){
            throw new CustomException("当前账号或密码不正确");
        }
        request.getServletContext().setAttribute("userMobile",mobile);
        // 生成token;
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("id", one.getId());
        String token = AppJwtUtil.getToken(tokenMap);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        return R.success(map);
    }
}
